package com.after.saas.common.utils;

import cn.hutool.json.JSONUtil;
import com.after.saas.common.constants.SortEnum;
import com.after.saas.common.model.vo.ValidBeanVO;
import com.after.saas.common.model.vo.ValidDemo;
import com.after.saas.common.validate.Group;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.groups.Default;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description
 * @Classname ValidatorUtil
 * @Author hjchen
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2022/11/4 16:18
 */
public class ValidatorUtil {

    private static Validator validator;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    public static <T> String validateBean(T bean, Class<?>... groups) {
        if (null == bean) {
            return "参数不能为空";
        }
        Set<ConstraintViolation<T>> validResult = validator.validate(bean, groups);
        if (CollectionUtils.isEmpty(validResult)) {
            return null;
        }
        Set<String> set = validResult.stream().map(ConstraintViolation::getMessage).collect(Collectors.toSet());
        return String.join("、", set);
    }

    public static void main(String[] args) {
        ValidBeanVO validBeanVO = new ValidBeanVO();
        ValidDemo demo = new ValidDemo();
        validBeanVO.setDesc("DEC");
        validBeanVO.setName("NO");
        validBeanVO.setCode("ABC2345678912345678");
        validBeanVO.setSort(SortEnum.ASC.getSort());
        validBeanVO.setStatus(3);
        validBeanVO.setMobile("1311111");
        demo.setSort(SortEnum.ASC.getSort());
        validBeanVO.setValidDemo(demo);
        List<ValidDemo> list = Collections.singletonList(demo);
        validBeanVO.setValidBeans(list);
        System.out.println(JSONUtil.toJsonStr(validBeanVO));
        System.out.println("result=" + validateBean(validBeanVO, Default.class,Group.AddGroup.class));
    }
}
